import React from "react"

// import Container from "./Container"
import Table from "./Table"
import Toolbar from "./Toolbar"
// import Statistics from "./Statistics"

interface IDraggableColumnProps {
	key?: string | number | undefined
	dataIndex?: string
	title: string | Function | React.ReactNode
	titleText?: string
	fixed?: boolean
	index?: number
	sortable?: boolean
	onCell?: any
}
interface DataListProps {
	data: any[]
	// statisticsPosition?: "top" | "bottom"
	maxHeight?: string
	buttons?: { label: string; type?: "primary" | "dashed" | "link" | "text" | "default"; onClick: () => void }[] | undefined
	columns: IDraggableColumnProps[] | any[]
	bordered?: boolean
	size?: "large" | "middle" | "small"
	rowKey?: string | (() => void)
	rowSelection?: object
	statisticDom?: (() => React.ReactNode | string | undefined) | React.ReactNode | string | undefined
	statisticText?: string | undefined
	onSort?: (columnName: string, sortOrder: "asc" | "desc") => void
	onExport?: () => void
	showRowSet?: boolean | undefined
	onColumnDrag?: (sourceIndex: number, destinationIndex: number) => void
	columnStyles?: React.CSSProperties[]
	onChange?: (pagination: any, filters: any, sorter: any, extra: any) => void
	pagination?:
		| {
				current: number
				pageSize: number
				total: number
				showSizeChanger?: boolean
				showTotal?: (total: number) => string
				showQuickJumper?: boolean
		  }
		| false
	loading?: boolean
	defaultScrollY?: number
	excelBlob?: Object
	excelName?: String
	sticky?: { offsetHeader?: number }
	summary?: any
	changeColumns?: (columns: any[]) => void
	components?: any
	scrollCustom?: any
	footer?: any
}

const DataList: React.FC<DataListProps> = ({
	data,
	// statisticsPosition = "top",
	// maxHeight,
	buttons,
	columns,
	columnStyles,
	statisticDom,
	onSort,
	onExport,
	showRowSet,
	onColumnDrag,
	onChange,
	loading,
	statisticText,
	pagination,
	defaultScrollY,
	rowSelection,
	summary,
	sticky,
	rowKey,
	scrollCustom,
	footer,
	...otherProps
}) => {
	const { useRef, useState, useEffect } = React
	const [loadingExtra, setLoadingExtra] = useState(false) //用于延时表格的loading状态，此延时为自适应高度的延时
	const tableWrapperRef = useRef(null)
	const [tableId] = useState(`t${Math.random().toFixed(5).substring(2)}`)
	const [toolbarId] = useState(`ttb${Math.random().toFixed(5).substring(2)}`)
	/**
	 * scrollY 表格垂直出现滚动的高度
	 */
	// const [scrollY, setScrollY] = useState(600)
	const [scrollC, setScrollC] = useState({ x: "100%", y: defaultScrollY ?? 600 } as
		| { x: "100%"; y: number }
		| { x: "100%"; y: undefined })

	// 根据页面高度动态设置表格垂直出现滚动的高度
	const resetScroll = () => {
		const headerHeight = document.querySelector(`#${tableId}`)?.querySelector("thead")?.clientHeight ?? 0
		const toolbarHeight = document.querySelector(`#${toolbarId}`)?.clientHeight ?? 0
		const tableHeight = document.querySelector(`#${tableId}`)?.clientHeight ?? 0
		const summaryHeight = document.querySelector(`#${tableId}`)?.querySelector(".ant-table-summary")?.clientHeight ?? 0
		if (tableWrapperRef.current) {
			const bufferHeight =
				(headerHeight as number) +
				(toolbarHeight as number) +
				summaryHeight +
				48 + //pagination 高度
				(document.querySelector(`#${tableId}`)?.querySelector(".statistic")?.clientHeight as number) //统计行高度
			const wrapHeight = (tableWrapperRef.current as unknown as HTMLDivElement).clientHeight
			console.log(wrapHeight, tableHeight, bufferHeight)
			setScrollC(preScrollC => {
				if (wrapHeight > (tableHeight as number)) return { x: "100%", y: undefined }
				const nextScrollY = wrapHeight - bufferHeight
				// 5是误差范围内
				if (!preScrollC.y || Math.abs(preScrollC.y - nextScrollY) > 5) {
					// console.log(nextScrollY, "next")
					return { x: "100%", y: nextScrollY }
				} else return preScrollC
			})
		}
		setLoadingExtra(false)
	}
	useEffect(() => {
		window.onresize = () => {
			setScrollC({ x: "100%", y: undefined })
			setTimeout(resetScroll, 1000)
		}
	}, [])
	useEffect(() => {
		if (!data || data.length === 0) return
		setScrollC({ x: "100%", y: undefined })
		setTimeout(resetScroll, 1000)
	}, [data])
	const [enableLoading, setEnableLoading] = useState(false) //用于启动extranLoading,避免第一次加载表格时的延时失效
	useEffect(() => {
		if (loading) {
			setLoadingExtra(true)
			setEnableLoading(true)
		} else {
			setTimeout(() => {
				if (enableLoading) setLoadingExtra(false)
			}, 1000)
		}
	}, [loading])

	return (
		<div className="ovh fl1" ref={tableWrapperRef}>
			<div id={toolbarId}>
				<Toolbar buttons={buttons} />
			</div>
			{/* {statisticsPosition === "top" && <Statistics data={data} statisticText={statisticText} statisticDom={statisticDom} />} */}
			<Table
				loading={loadingExtra}
				footer={footer}
				data={data}
				columns={columns}
				onSort={onSort}
				onExport={onExport}
				showRowSet={showRowSet}
				onColumnDrag={onColumnDrag}
				columnStyles={columnStyles}
				onChange={onChange}
				scroll={scrollCustom || scrollC}
				tableId={tableId}
				statisticDom={statisticDom}
				statisticText={statisticText}
				pagination={pagination}
				rowSelection={rowSelection}
				summary={summary}
				sticky={sticky}
				rowKey={rowKey}
				{...otherProps}
			/>
			{/* {statisticsPosition === "bottom" && <Statistics data={data} statisticText={statisticText} statisticDom={statisticDom} />} */}
		</div>
	)
}

export default DataList
